package com.n5x.common.interceptor;

import com.n5x.common.base.JsonModel;
import com.n5x.common.base.ResponseCode;
import com.n5x.common.base.TokenModel;
import com.n5x.controller.BaseController;
import net.sf.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class UserHandlerInterceptor extends BaseController implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getParameter("token");

        try {
            TokenModel tokenModel = getTokenModelByToken(token);
            if (null == tokenModel) {
                JsonModel jsonModel = getResultError(ResponseCode.Common_NotLogIn, "用户未登陆");
                this.outJsonModel(jsonModel);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[拦截器报错]e:", e.toString());
            JsonModel jsonModel = getResultError(ResponseCode.Common_Error, "检测拦截用户报错:" + e.toString());
            this.outJsonModel(jsonModel);
            return false;
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    private void outJsonModel(JsonModel jsonModel) throws IOException {
        JSONObject jsonObject = JSONObject.fromObject(jsonModel);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.append(jsonObject.toString());
    }
}
